package com.server.modules.api.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/9/23.
 */
public class ApiInterceptor   implements HandlerInterceptor {

    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            HandlerMethod handlerMethod = null;
            if (handler instanceof DefaultServletHttpRequestHandler) {
                handlerMethod = (HandlerMethod) handler;
                logger.info( handlerMethod.getMethod().getName() );
                Map map = request.getParameterMap();
                Set keSet = map.entrySet();
                for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
                    Map.Entry me = (Map.Entry) itr.next();
                    Object ok = me.getKey();
                    Object ov = me.getValue();
                    String[] value = new String[1];
                    if (ov instanceof String[]) {
                        value = (String[]) ov;
                    } else {
                        value[0] = ov.toString();
                    }
                    for (int k = 0; k < value.length; k++) {
                        logger.info( ok + "=" + value[k] );
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
